import { DownOutlined } from '@ant-design/icons';
import { useQueryClient } from '@tanstack/react-query';
import { Button, Card, message, Popover, Splitter, Switch, Tree, TreeProps } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { DataNode } from 'antd/es/tree';
import React, { useState, useEffect, useCallback, Key } from 'react';

import departmentService from '@/api/services/security/departmentService';
import userService from '@/api/services/security/userService';
import { Iconify } from '@/components/icon';
import TipIconButton from '@/components/icon/tooltip-icon-button';
import { UserDepartmentModal } from '@/pages/management/system/user/user-department-modal';
import { usePathname, useRouter } from '@/router/hooks';
import { datetime } from '@/utils/format-date';
import { pagination } from '@/utils/pagination';
import { hasPermission } from '@/utils/permission';

import UserModal from './user-modal';
import { UserPositionModal } from './user-position-modal';
import { RoleModal } from './user-role-modal';
import UserSearch, { UserSearchForm } from './user-seach';

import type { ListData, ModalProps, UserInfo } from '#/entity';
import { BasicStatus } from '#/enum';

export default function UserInfoIndex() {
  // 定义数据-------------------------------------------------------------------------------------
  const [tableData, setTableData] = useState<ListData<UserInfo>>();

  const { push } = useRouter();
  const pathname = usePathname();
  const queryClient = useQueryClient();
  // 添加分页状态
  const [searchForm, setSearchForm] = useState<UserSearchForm>({
    take: 10,
    page: 1,
  });
  // 添加选择相关状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [departmentSelectedRowKeys, setDepartmentSelectedRowKeys] = useState<React.Key[]>([]);
  // 定义函数-------------------------------------------------------------------------------------
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  // userModalProps------------------------------------------------------------------------------
  const [treeData, setTreeData] = useState<DataNode[]>();
  const handleDepartmentData = useCallback((data) => {
    data.forEach((item) => {
      if (item.departementList && item.departementList.length > 0) {
        item.children = item.departementList;
        handleDepartmentData(item.children);
      }
      item.title = `${item.name}(${item.directUserCount})`;
      item.key = item.id.toString();
    });
  }, []);
  useEffect(() => {
    if (hasPermission('DEPARTMENT:DEPARTMENT:READ')) {
      departmentService.getDepartmentsList().then((res) => {
        handleDepartmentData(res);
        setTreeData(res);
      });
    }
  }, [handleDepartmentData]);

  const [userModalProps, setUserModalProps] = useState<ModalProps<UserInfo>>({
    formValue: {
      id: '0',
      name: '',
    },
    title: '',
    show: false,
    onOk: () => {
      setUserModalProps((prev) => ({ ...prev, show: false }));
      setSearchForm((prev) => ({ ...prev }));
    },
    onCancel: () => {
      setUserModalProps((prev) => ({ ...prev, show: false }));
    },
  });

  // roleModalProps------------------------------------------------------------------------------
  const [roleModalProps, setRoleModalProps] = useState({
    formValue: {},
    title: '',
    show: false,
    onOk: () => {
      setRoleModalProps((prev) => ({ ...prev, show: false }));
    },
    onCancel: () => {
      setSearchForm((prev) => ({ ...prev }));
      setRoleModalProps((prev) => ({ ...prev, show: false }));
    },
  });
  const [departmentModalProps, setDepartmentModalProps] = useState<ModalProps<UserInfo>>({
    formValue: { id: '0', name: '', meta: {} },
    title: '',
    show: false,
    onOk: () => {
      setDepartmentModalProps((prev) => ({ ...prev, show: false }));
      setSearchForm((prev) => ({ ...prev }));
    },
    onCancel: () => {
      setDepartmentModalProps((prev) => ({ ...prev, show: false }));
    },
  });
  const [positionModalProps, setPositionModalProps] = useState<ModalProps<UserInfo>>({
    formValue: { id: '0', name: '', meta: {} },
    title: '',
    show: false,
    onOk: () => {
      setPositionModalProps((prev) => ({ ...prev, show: false }));
      setSearchForm((prev) => ({ ...prev }));
    },
    onCancel: () => {
      setPositionModalProps((prev) => ({ ...prev, show: false }));
    },
  });
  const onEditRole = async (record: UserInfo) => {
    setRoleModalProps((prev) => ({
      ...prev,
      title: '添加角色',
      show: true,
      formValue: {
        ...record,
        roles: record.roles,
      },
    }));
  };
  const onEditDepartment = async (record: UserInfo) => {
    setDepartmentModalProps((prev) => ({
      ...prev,
      title: '修改用户部门',
      show: true,
      formValue: record,
    }));
  };
  const onEditPosition = async (record: UserInfo) => {
    setPositionModalProps((prev) => ({
      ...prev,
      title: '修改用户岗位',
      show: true,
      formValue: record,
    }));
  };
  // 定义事件-----------------------------------------------------------
  const onCreate = () => {
    setUserModalProps((prev) => ({
      ...prev,
      title: '新增用户',
      show: true,
      formValue: {
        id: '0',
        name: '',
      },
    }));
  };
  const onEdit = (record: UserInfo) => {
    setUserModalProps((prev) => ({
      ...prev,
      title: '编辑用户',
      show: true,
      formValue: record,
    }));
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const onResetPassword = async (record: UserInfo) => {
    const response = await userService.resetPassword(record.id);
    if (response > 0) {
      message.success('密码重置成功');
      await queryClient.invalidateQueries({ queryKey: ['user'] });
    } else {
      message.error('密码重置失败');
    }
  };
  // 获取user数据-------------------------------------------------------------------------------------

  useEffect(() => {
    // 初始化tableData
    if (hasPermission('SECURITY:USER:READ')) {
      if (searchForm.departmentId) {
        userService.getDepartmentUserList(searchForm).then((res) => {
          setTableData(res);
        });
      } else {
        userService.getUserList(searchForm).then((res) => {
          setTableData(res);
        });
      }
    }
  }, [searchForm]);

  const resetSearchData = () => {
    setDepartmentSelectedRowKeys([]);
    setSearchForm({ page: 1, take: 10 });
  };

  const allIsEnable = async () => {
    if (selectedRowKeys.length <= 0) {
      message.warning('请选择要启用的用户');
      return;
    }
    userService.enableUsers({ ids: selectedRowKeys }).then((response) => {
      if (response > 0) {
        message.success('所选ID全部启用成功');
        setSearchForm((prev) => ({ ...prev }));

        setSelectedRowKeys([]); // 清空选择
      } else {
        message.error('所选ID全部启用失败');
      }
    });
  };

  const allIsDisable = async () => {
    if (selectedRowKeys.length <= 0) {
      message.warning('请选择要禁用的用户');
      return;
    }

    userService.disableUsers({ ids: selectedRowKeys }).then((response) => {
      if (response > 0) {
        message.success('所选ID全部禁用成功');
        setSearchForm((prev) => ({ ...prev }));
        setSelectedRowKeys([]); // 清空选择
      } else {
        message.error('所选ID全部禁用失败');
      }
    });
  };
  const onStatusChange = async (record: UserInfo) => {
    let response;
    if (record.status === BasicStatus.ENABLE) {
      response = await userService.disableUsers({ ids: [record.id] });
    } else {
      response = await userService.enableUsers({ ids: [record.id] });
    }
    if (response > 0) {
      message.success(record.status === BasicStatus.ENABLE ? '禁用成功' : '启用成功');
      setSearchForm((prev) => ({ ...prev }));
    } else {
      message.error(record.status === BasicStatus.ENABLE ? '禁用失败' : '启用失败');
    }
  };

  const columns: ColumnsType<UserInfo> = [
    {
      title: '账号',
      dataIndex: 'code',
      width: 150,
    },
    {
      fixed: 'left',
      title: '名称',
      dataIndex: 'name',
      width: 150,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width: 200,
    },

    {
      title: '手机',
      dataIndex: 'mobile',
      width: 100,
    },
    {
      width: 150,
      title: '部门',
      dataIndex: 'department',
      render: (_, record) => {
        if (record.meta.DEPARTMENT.length > 0) {
          return (
            <Button
              style={{
                cursor: hasPermission('DEPARTMENT:DEPARTMENT:UPDATE') ? 'pointer' : 'not-allowed',
              }}
              color="primary"
              variant="link"
              onClick={() => {
                if (hasPermission('DEPARTMENT:DEPARTMENT:UPDATE')) {
                  onEditDepartment(record);
                }
              }}
            >
              <Popover
                content={record?.meta?.DEPARTMENT.map((item) => {
                  return (
                    <div key={item.id} className="flex items-center gap-2">
                      <span>{item.name}</span>
                    </div>
                  );
                })}
              >
                <span
                  style={{
                    maxWidth: '120px',
                    overflow: 'hidden',
                    whiteSpace: 'nowrap',
                    textOverflow: 'ellipsis',
                  }}
                >
                  {record.meta.DEPARTMENT.map((item) => item.name).join(',')}
                </span>
              </Popover>
            </Button>
          );
        }
        return (
          <TipIconButton
            style={{
              cursor: hasPermission('DEPARTMENT:DEPARTMENT:UPDATE') ? 'pointer' : 'not-allowed',
            }}
            onClick={() => {
              if (hasPermission('DEPARTMENT:DEPARTMENT:UPDATE')) {
                onEditDepartment(record);
              }
            }}
            tipText="添加部门"
          >
            <Iconify icon="material-symbols:account-tree" size={20} />
          </TipIconButton>
        );
      },
    },
    {
      width: 150,
      title: '岗位',
      dataIndex: 'position',
      render: (_, record) => {
        if (record.meta.POSITION?.length > 0) {
          return (
            <Button
              style={{
                cursor: hasPermission('DEPARTMENT:POSITION:UPDATE') ? 'pointer' : 'not-allowed',
              }}
              color="primary"
              variant="link"
              onClick={() => {
                if (hasPermission('DEPARTMENT:DEPARTMENT:UPDATE')) {
                  onEditPosition(record);
                }
              }}
            >
              <Popover
                content={record?.meta?.POSITION.map((item) => {
                  return (
                    <div key={item.code} className="flex items-center gap-2">
                      <span>{item.name}</span>
                    </div>
                  );
                })}
              >
                <span
                  style={{
                    maxWidth: '120px',
                    overflow: 'hidden',
                    whiteSpace: 'nowrap',
                    textOverflow: 'ellipsis',
                  }}
                >
                  {record?.meta?.POSITION.map((item) => item.name).join(',')}
                </span>
              </Popover>
            </Button>
          );
        }
        return (
          <TipIconButton
            style={{
              cursor: hasPermission('DEPARTMENT:DEPARTMENT:UPDATE') ? 'pointer' : 'not-allowed',
            }}
            onClick={() => {
              if (hasPermission('DEPARTMENT:DEPARTMENT:UPDATE')) {
                onEditPosition(record);
              }
            }}
            tipText="添加岗位"
          >
            <Iconify icon="material-symbols:assignment-ind" size={20} />
          </TipIconButton>
        );
      },
    },
    {
      title: '角色',
      dataIndex: 'roles',
      width: 150,
      render: (_, record) => {
        if (record.roles.length > 0) {
          return (
            <Button
              style={{
                cursor: hasPermission('SECURITY:ROLE:ASSIGN') ? 'pointer' : 'not-allowed',
              }}
              color="primary"
              variant="link"
              onClick={() => {
                if (hasPermission('SECURITY:ROLE:ASSIGN')) {
                  onEditRole(record);
                }
              }}
            >
              <Popover
                content={record?.roles.map((item) => {
                  return (
                    <div key={item.id} className="flex items-center gap-2">
                      <span>{item.name}</span>
                    </div>
                  );
                })}
              >
                <span
                  style={{
                    maxWidth: '120px',
                    overflow: 'hidden',
                    whiteSpace: 'nowrap',
                    textOverflow: 'ellipsis',
                  }}
                >
                  {record?.roles.map((item) => item.name).join(',')}
                </span>
              </Popover>
            </Button>
          );
        }
        return (
          <TipIconButton
            style={{
              cursor: hasPermission('SECURITY:ROLE:ASSIGN') ? 'pointer' : 'not-allowed',
            }}
            onClick={() => {
              if (hasPermission('SECURITY:ROLE:ASSIGN')) {
                onEditRole(record);
              }
            }}
            tipText="添加角色"
          >
            <Iconify icon="mdi:account-group" size={20} />
          </TipIconButton>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 80,
      render: (status: BasicStatus, record: UserInfo) => (
        <Switch
          checked={status === BasicStatus.ENABLE}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          onChange={() => onStatusChange(record)}
          disabled={!hasPermission('SECURITY:USER:UPDATE_IS_DISABLED')}
        />
      ),
    },
    {
      title: '创建时间',
      width: 200,
      dataIndex: 'createAt',
      render: (createAt: number[]) => datetime(createAt),
    },
    { title: '备注', dataIndex: 'remark', width: 100 },

    {
      fixed: 'right',
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 150,
      render: (_: any, record: UserInfo) => (
        <div className="flex w-full justify-center text-gray">
          {hasPermission('SECURITY:USER:WRITE') && (
            <TipIconButton onClick={() => onEdit(record)} tipText="编辑用户">
              <Iconify icon="solar:pen-bold-duotone" size={18} />
            </TipIconButton>
          )}

          <TipIconButton
            onClick={() => {
              push(`${pathname}/${record.id}`);
            }}
            tipText="查看详情"
          >
            <Iconify icon="mdi:card-account-details" size={18} />
          </TipIconButton>
          {hasPermission('SECURITY:USER:RESET_PASSWORD') && (
            <TipIconButton onClick={() => onResetPassword(record)} tipText="重置密码">
              <Iconify icon="mdi:lock-reset" size={18} />
            </TipIconButton>
          )}
        </div>
      ),
    },
  ];
  const handleDataFromUserSearch = (data: any) => {
    setSearchForm((prev) => ({
      ...prev,
      name: data.name,
      code: data.code,
      status: data.status,
    }));
  };

  const right = (
    <>
      <UserSearch onReset={resetSearchData} onSendData={handleDataFromUserSearch} />
      <br />
      <Card
        style={{ height: '300px', width: '100%' }}
        title="用户列表"
        extra={
          <div className="flex items-center gap-2">
            {hasPermission('SECURITY:USER:UPDATE_IS_DISABLED') && (
              <Button onClick={() => allIsEnable()}>启用</Button>
            )}
            {hasPermission('SECURITY:USER:UPDATE_IS_DISABLED') && (
              <Button onClick={() => allIsDisable()}>禁用</Button>
            )}
            {hasPermission('SECURITY:USER:WRITE') && (
              <Button
                type="primary"
                // disabled={!hasPermission('SECURITY:USER:CREATE')}
                onClick={() => onCreate()}
              >
                新增
              </Button>
            )}
          </div>
        }
      >
        <Table
          rowSelection={rowSelection}
          rowKey="id"
          size="small"
          scroll={{
            x: 'max-content',
            // y: 'calc(100vh - 470px)',
          }}
          columns={columns}
          dataSource={tableData?.data}
          pagination={pagination({
            page: searchForm,
            onPageChange: (page, rows) => {
              setSearchForm((prev) => ({
                ...prev,
                page,
                take: rows,
              }));
            },
            count: tableData?.count,
          })}
        />
        <UserModal {...userModalProps} />
        <RoleModal {...roleModalProps} />
        <UserDepartmentModal {...departmentModalProps} />
        <UserPositionModal {...positionModalProps} />
      </Card>
    </>
  );
  const onSelect: TreeProps['onSelect'] = (selectedKeys: Key[]) => {
    setDepartmentSelectedRowKeys(selectedKeys);
    setSearchForm((prev) => ({
      ...prev,
      page: 1,
      departmentId: selectedKeys[0] as number,
    }));
  };

  const tree = (
    <Card
      title="部门"
      style={{ marginTop: '-2px', marginLeft: '-2px', height: '100%', width: '100%' }}
    >
      <Tree
        autoExpandParent
        showLine
        selectedKeys={departmentSelectedRowKeys}
        switcherIcon={<DownOutlined />}
        onSelect={onSelect}
        treeData={treeData}
      />
    </Card>
  );
  return (
    <Splitter style={{ boxShadow: '0 0 10px rgba(0, 0, 0, 0.1)' }}>
      {hasPermission('DEPARTMENT:DEPARTMENT:READ') && (
        <Splitter.Panel
          // size="0%"
          size="14%"
          resizable
        >
          <div style={{ width: '100%', height: '100%' }}>{tree}</div>
        </Splitter.Panel>
      )}
      <Splitter.Panel>
        <div style={{ height: '100%', width: '100%' }}>{right}</div>
      </Splitter.Panel>
    </Splitter>
  );
}
